<template>
  <div class="recording-control">
    <div class="control-panel">
      <h2>脑波录制控制</h2>
      
      <!-- 设备连接按钮 -->
      <button 
        :class="['btn', 'device-btn', { 'connected': isDeviceConnected, 'connecting': isConnecting }]"
        @click="toggleDevice"
        :disabled="isConnecting"
      >
        {{ isConnecting ? '连接中...' : (isDeviceConnected ? '断开设备' : '连接设备') }}
      </button>
      
      <!-- 录制按钮 -->
      <button 
        :class="['btn', 'record-btn', { 'recording': isRecording, 'starting': isStartingRecord }]"
        @click="toggleRecording"
        :disabled="!isDeviceConnected || isStartingRecord"
      >
        {{ isStartingRecord ? '启动中...' : (isRecording ? '停止录制' : '开始录制') }}
      </button>
      
      <!-- 录制时间显示 -->
      <div v-if="isRecording" class="recording-info">
        <div class="recording-indicator">
          <span class="dot"></span>
          正在录制中...
        </div>
        <div class="recording-time">
          录制时间: {{ formatTime(recordingTime) }}
        </div>
      </div>
      
      <!-- 错误信息显示 -->
      <div v-if="deviceStatus.error_message" class="error-info">
        <div class="error-message">
          <span class="error-icon">⚠️</span>
          {{ deviceStatus.error_message }}
        </div>
      </div>
      
      <!-- 状态显示 -->
      <div class="status-info">
        <div class="status-item">
          <span class="label">设备状态:</span>
          <span :class="['status', { 'connected': isDeviceConnected }]">
            {{ isDeviceConnected ? '已连接' : '未连接' }}
          </span>
        </div>
        <div class="status-item" v-if="isDeviceConnected">
          <span class="label">信号质量:</span>
          <span :class="['status', 'signal-' + deviceStatus.signal_quality]">
            {{ getSignalQualityText(deviceStatus.signal_quality) }}
          </span>
        </div>
        <div class="status-item" v-if="isDeviceConnected && deviceStatus.battery_level > 0">
          <span class="label">电池电量:</span>
          <span :class="['status', 'battery-' + getBatteryLevel(deviceStatus.battery_level)]">
            {{ deviceStatus.battery_level }}%
          </span>
        </div>
        <div class="status-item">
          <span class="label">录制状态:</span>
          <span :class="['status', { 'recording': isRecording }]">
            {{ isRecording ? '录制中' : '待机' }}
          </span>
        </div>
        <div class="status-item" v-if="sessionId">
          <span class="label">会话ID:</span>
          <span class="status session-id">
            {{ sessionId.substring(0, 8) }}...
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BrainWaveClient from '../utils/BrainWaveClient.js';

export default {
  name: 'RecordingControl',
  props: {
    brainWaveClient: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      isDeviceConnected: false,
      isRecording: false,
      recordingTime: 0,
      recordingTimer: null,
      deviceStatus: {
        connected: false,
        signal_quality: 'unknown',
        battery_level: 0,
        error_message: ''
      },
      sessionId: null,
      isConnecting: false,
      isStartingRecord: false
    }
  },
  methods: {
    // 切换设备连接状态
    async toggleDevice() {
      if (this.isConnecting) return;
      
      if (this.isRecording && this.isDeviceConnected) {
        // 如果正在录制且设备已连接，先停止录制再断开设备
        await this.stopRecording();
        await this.disconnectDevice();
        return;
      }
      
      if (this.isDeviceConnected) {
        await this.disconnectDevice();
      } else {
        await this.connectDevice();
      }
    },
    
    // 连接设备
    async connectDevice() {
      if (!this.brainWaveClient) {
        console.error('BrainWaveClient 未初始化');
        return;
      }
      
      this.isConnecting = true;
      this.deviceStatus.error_message = '';
      
      try {
        // 连接设备
        const success = await this.brainWaveClient.connect();
        
        if (success) {
          this.isDeviceConnected = true;
          this.deviceStatus.connected = true;
          this.sessionId = this.brainWaveClient.sessionId;
          
          // 连接WebSocket
          this.brainWaveClient.connectWebSocket();
          
          console.log('设备连接成功，会话ID:', this.sessionId);
          
          // 定期获取设备状态
          this.startStatusPolling();
        } else {
          this.deviceStatus.error_message = '设备连接失败';
          console.error('设备连接失败');
        }
      } catch (error) {
        this.deviceStatus.error_message = '连接设备时发生错误';
        console.error('连接设备错误:', error);
      } finally {
        this.isConnecting = false;
      }
    },
    
    // 断开设备
    async disconnectDevice() {
      if (!this.brainWaveClient) return;
      
      try {
        // 先停止录制（如果正在录制）
        if (this.isRecording) {
          await this.stopRecording();
        }
        
        // 断开连接
        await this.brainWaveClient.disconnect();
        
        this.isDeviceConnected = false;
        this.deviceStatus.connected = false;
        this.sessionId = null;
        this.stopStatusPolling();
        
        console.log('设备已断开');
      } catch (error) {
        console.error('断开设备错误:', error);
      }
    },
    
    // 开始状态轮询
    startStatusPolling() {
      if (this.statusTimer) {
        clearInterval(this.statusTimer);
      }
      
      this.statusTimer = setInterval(async () => {
        if (this.sessionId && this.brainWaveClient) {
          try {
            const status = await this.brainWaveClient.getDeviceStatus();
            if (status) {
              this.deviceStatus = {
                ...this.deviceStatus,
                signal_quality: status.signal_quality || 'unknown',
                battery_level: status.battery_level || 0
              };
            } else {
              // 如果获取状态失败，保持当前状态或设置默认值
              this.deviceStatus = {
                ...this.deviceStatus,
                signal_quality: 'disconnected',
                battery_level: 0
              };
            }
          } catch (error) {
            console.error('获取设备状态失败:', error);
            this.deviceStatus = {
              ...this.deviceStatus,
              signal_quality: 'error',
              battery_level: 0
            };
          }
        }
      }, 5000); // 每5秒检查一次状态
    },
    
    // 停止状态轮询
    stopStatusPolling() {
      if (this.statusTimer) {
        clearInterval(this.statusTimer);
        this.statusTimer = null;
      }
    },
    
    // 切换录制状态
    async toggleRecording() {
      if (!this.isDeviceConnected || this.isStartingRecord) {
        return; // 设备未连接时不允许录制
      }
      
      if (this.isRecording) {
        await this.stopRecording();
      } else {
        await this.startRecording();
      }
    },
    
    // 开始录制
    async startRecording() {
      if (!this.brainWaveClient || !this.sessionId) {
        console.error('无法开始录制：客户端或会话未初始化');
        return;
      }
      console.log('startRecording 开始录制: 会话ID: ', this.sessionId);
      this.isStartingRecord = true;
      
      try {
        const result = await this.brainWaveClient.startRecording(this.sessionId);
        console.log('startRecording 开始录制: 结果: ', result);
        if (result) {
          this.isRecording = true;
          this.recordingTime = 0;
          this.recordingTimer = setInterval(() => {
            this.recordingTime++;
          }, 1000);
          
          console.log('录制已开始');
        } else {
          console.error('开始录制失败');
          this.deviceStatus.error_message = '开始录制失败';
        }
      } catch (error) {
        console.error('开始录制错误:', error);
        this.deviceStatus.error_message = '开始录制时发生错误';
      } finally {
        this.isStartingRecord = false;
      }
    },
    
    // 停止录制
    async stopRecording() {
      if (!this.brainWaveClient || !this.sessionId) {
        console.error('无法停止录制：客户端或会话未初始化');
        return;
      }
      
      try {
        const result = await this.brainWaveClient.stopRecording(this.sessionId);
        
        if (result.success) {
          this.isRecording = false;
          
          if (this.recordingTimer) {
            clearInterval(this.recordingTimer);
            this.recordingTimer = null;
          }
          
          console.log('录制已停止，录制时长:', this.formatTime(this.recordingTime));
        } else {
          console.error('停止录制失败:', result.message);
          this.deviceStatus.error_message = result.message || '停止录制失败';
        }
      } catch (error) {
        console.error('停止录制错误:', error);
        this.deviceStatus.error_message = '停止录制时发生错误';
      }
    },
    
    // 格式化时间显示
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      if (hours > 0) {
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      } else {
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      }
    },
    
    // 获取信号质量文本
    getSignalQualityText(quality) {
      const qualityMap = {
        'excellent': '优秀',
        'good': '良好',
        'fair': '一般',
        'poor': '较差',
        'unknown': '未知'
      };
      return qualityMap[quality] || '未知';
    },
    
    // 获取电池电量等级
    getBatteryLevel(level) {
      if (level >= 80) return 'high';
      if (level >= 50) return 'medium';
      if (level >= 20) return 'low';
      return 'critical';
    }
  },
  
  beforeUnmount() {
    // 组件销毁前清理定时器和连接
    if (this.recordingTimer) {
      clearInterval(this.recordingTimer);
    }
    
    this.stopStatusPolling();
    
    // 如果设备已连接，尝试断开
    if (this.isDeviceConnected) {
      this.disconnectDevice();
    }
  }
}
</script>

<style scoped>
.recording-control {
  width: 100%;
  height: 100%;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.control-panel {
  background: linear-gradient(135deg, #87CEEB 0%, #B0E0E6 50%, #E0F6FF 100%);
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(135, 206, 235, 0.3);
  border: none;
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.control-panel::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at 20% 80%, rgba(0, 191, 255, 0.1) 0%, transparent 50%),
              radial-gradient(circle at 80% 20%, rgba(135, 206, 235, 0.1) 0%, transparent 50%);
  pointer-events: none;
  animation: shimmer 4s ease-in-out infinite alternate;
}

h2 {
  text-align: center;
  color: #4682B4;
  margin-bottom: 20px;
  font-size: 1.4rem;
  text-shadow: 0 2px 4px rgba(70, 130, 180, 0.3);
  position: relative;
  z-index: 1;
}

.btn {
  display: block;
  width: 100%;
  padding: 12px 18px;
  margin: 10px 0;
  border: none;
  border-radius: 10px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: none;
  position: relative;
  z-index: 1;
}

.device-btn {
  background-color: #2196F3;
  color: white;
}

.device-btn:hover {
  background-color: #1976D2;
}

.device-btn.connected {
  background-color: #4CAF50;
}

.device-btn.connected:hover {
  background-color: #45a049;
}

.device-btn.connecting {
  background-color: #FF9800;
  animation: pulse 1.5s infinite;
}

.device-btn.connecting:hover {
  background-color: #F57C00;
}

.record-btn {
  background-color: #FF5722;
  color: white;
}

.record-btn:hover:not(:disabled) {
  background-color: #E64A19;
}

.record-btn.recording {
  background-color: #f44336;
  animation: pulse 2s infinite;
}

.record-btn.starting {
  background-color: #FF9800;
  animation: pulse 1.5s infinite;
}

.btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

.recording-info {
  margin: 15px 0;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  border-left: 4px solid #4682B4;
  position: relative;
  z-index: 1;
}

.recording-indicator {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 600;
  color: #e65100;
}

.dot {
  width: 12px;
  height: 12px;
  background-color: #f44336;
  border-radius: 50%;
  margin-right: 10px;
  animation: blink 1s infinite;
}

.recording-time {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.status-info {
  margin-top: 15px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  position: relative;
  z-index: 1;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 600;
  color: #666;
}

.status {
  font-weight: 600;
  color: #999;
}

.status.connected {
  color: #4CAF50;
}

.status.recording {
  color: #f44336;
}

.status.signal-excellent {
  color: #4CAF50;
}

.status.signal-good {
  color: #8BC34A;
}

.status.signal-fair {
  color: #FF9800;
}

.status.signal-poor {
  color: #f44336;
}

.status.signal-unknown {
  color: #999;
}

.status.battery-high {
  color: #4CAF50;
}

.status.battery-medium {
  color: #FF9800;
}

.status.battery-low {
  color: #f44336;
}

.status.battery-critical {
  color: #d32f2f;
  font-weight: bold;
}

.status.session-id {
  font-family: monospace;
  font-size: 0.9em;
  color: #666;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

@keyframes shimmer {
  0% {
    opacity: 0.5;
  }
  100% {
    opacity: 0.8;
  }
}

.error-info {
  margin: 15px 0;
  padding: 12px;
  background-color: rgba(255, 235, 238, 0.9);
  border-radius: 8px;
  border-left: 4px solid #f44336;
  position: relative;
  z-index: 1;
}

.error-message {
  display: flex;
  align-items: center;
  color: #d32f2f;
  font-weight: 500;
}

.error-icon {
  margin-right: 8px;
  font-size: 1.1em;
}
</style>